import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import dashboard from './views/dashboard.vue'
import reminder from './views/reminder.vue'
import users from './views/users.vue'
import settings from './views/settings.vue'
import { isAdmin } from './utils/authGuard'

import analytics from './views/analytics.vue'
import fintech from './views/fintech.vue'
import customers from './views/customers.vue'
import messages from './views/messages.vue'
import Signin from './views/Signin.vue'
import Signup from './views/Signup.vue'
import ResetPassword from './views/ResetPassword.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'dashboard',
    component: dashboard
  },
  {
    path: '/dashboard/analytics',
    name: 'analytics',
    component: analytics
  },
  {
    path: '/dashboard/fintech',
    name: 'fintech',
    component: fintech
  },
  {
    path: '/ecommerce/customers',
    name: 'customers',
    component: customers
  },
  {
    path: '/messages',
    name: 'messages',
    component: messages
  },
  {
    path: '/reminder',
    name: 'reminder',
    component: reminder
  },
  {
    path: '/users',
    name: 'users',
    component: users,
    meta: {
      requiresAdmin: true
    }
  },
  {
    path: '/settings',
    name: 'settings',
    component: settings
  },
  {
    path: '/signin',
    name: 'signin',
    component: Signin,
    meta: {
      hideLayout: true
    }
  },
  {
    path: '/signup',
    name: 'signup',
    component: Signup
  },
  {
    path: '/reset-password',
    name: 'reset-password',
    component: ResetPassword
  },

]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫：未登录时强制跳转登录页
router.beforeEach((to) => {
  const publicPaths = new Set<string>(['/signin', '/signup', '/reset-password'])
  const token = typeof window !== 'undefined' ? localStorage.getItem('access_token') : null

  // 已登录访问登录页，跳回原目标或首页
  if (token && to.path === '/signin') {
    const redirect = (to.query as any)?.redirect as string | undefined
    return { path: redirect || '/' }
  }

  // 未登录访问受保护页，跳转到登录页
  if (!token && !publicPaths.has(to.path)) {
    return { path: '/signin', query: { redirect: to.fullPath } }
  }

  // 检查管理员权限
  if (to.meta?.requiresAdmin && !isAdmin()) {
    return { path: '/' }
  }

  return true
})

export default router

